/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.zhuangfei.ohos_timetableview.slice;

import com.zhuangfei.ohos_timetableview.ResourceTable;
import com.zhuangfei.ohos_timetableview.base.BaseAbilitySlice;
import com.zhuangfei.ohos_timetableview.bean.WeekChooseBean;
import com.zhuangfei.ohos_timetableview.dialog.ChooseWeekDialog;
import com.zhuangfei.ohos_timetableview.dialog.TipsDialogUtil;
import com.zhuangfei.ohos_timetableview.dialog.ToastViewDialog;
import com.zhuangfei.ohos_timetableview.model.MySubject;
import com.zhuangfei.ohos_timetableview.model.SubjectRepertory;
import com.zhuangfei.ohos_timetableview.spinner.MaterialSpinner;
import com.zhuangfei.ohos_timetableview.utils.LogUtils;
import com.zhuangfei.timetable.TimetableView;
import com.zhuangfei.timetable.listener.ISchedule;
import com.zhuangfei.timetable.listener.IWeekView;
import com.zhuangfei.timetable.listener.OnItemBuildAdapter;
import com.zhuangfei.timetable.model.Schedule;
import com.zhuangfei.timetable.view.WeekView;

import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * SimpleSlice
 *
 * @since 2021-03-29
 */
public class SimpleSlice extends BaseAbilitySlice implements Component.ClickedListener {
    /**
     * 广告链接
     */
    public static final String AD_URL =
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1545749786636&di=fd5483be8b08b"
                    + "2e1f0485e772dadace4&imgtype=0&src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F5f9fae85770bb289f790e08d"
                    + "778516d128f0492a114a8-TNyOSi_fw658";

    /**
     * 控件
     */
    TimetableView mTimetableView;
    WeekView mWeekView;
    Intent intents;
    DirectionalLayout layout;
    Text titleTextView;
    List<MySubject> mySubjects;


    /**
     * 记录切换的周次，不一定是当前周
     */

    int target = -1;
    private TipsDialogUtil tipsDialogUtil;


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_base_func);
        initViews();
        intents = intent;
    }

    private void initViews() {
        titleTextView = (Text) findComponentById(ResourceTable.Id_id_title);
        layout = (DirectionalLayout) findComponentById(ResourceTable.Id_id_layout);
        MaterialSpinner spinner = (MaterialSpinner) findComponentById(ResourceTable.Id_id_more);

        layout.setClickedListener(this);

        spinner.setShowFalse(true);

        initTimetableView();
        requestData();
    }

    @Override
    public void onActive() {
        super.onActive();
        mTimetableView.onDateBuildListener()
                .onHighLight();
    }

    EventHandler runner = new EventHandler(EventRunner.create()) {
        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            mySubjects = SubjectRepertory.loadDefaultSubjects();
            MySubject adSubject = new MySubject();
            adSubject.setName("【广告】");
            adSubject.setStart(1);
            adSubject.setStep(2);
            adSubject.setDay(7);
            List<Integer> list = new ArrayList<>();
            for (int i = 1; i <= 20; i++) {
                list.add(i);
            }
            adSubject.setWeekList(list);
            adSubject.setUrl(AD_URL);
            mySubjects.add(adSubject);
            SimpleSlice.this.getUITaskDispatcher().asyncDispatch(() -> {
                mWeekView.source(mySubjects).showView();
                mTimetableView.source(mySubjects).showView();
                tipsDialogUtil.dismiss();
            });

        }
    };

    /**
     * 2秒后刷新界面，模拟网络请求
     */
    private void requestData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    SimpleSlice.this.getUITaskDispatcher().asyncDispatch(() -> {
                        tipsDialogUtil = new TipsDialogUtil(SimpleSlice.this);
                        tipsDialogUtil.show("Tips", "模拟请求网络中..");
                    });

                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    String errorString = e.toString();
                }
                runner.sendEvent(InnerEvent.get());
            }
        }).start();
    }


    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_id_layout:
                /**
                 * 如果周次选择已经显示了，那么将它隐藏，更新课程、日期
                 */
                if (mWeekView.isShowing()) {
                    hideWeekView();
                } else {
                    showWeekView();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 初始化课程控件
     */
    private void initTimetableView() {
        mWeekView = (WeekView) findComponentById(ResourceTable.Id_id_weekview);
        mTimetableView = (TimetableView) findComponentById(ResourceTable.Id_id_timetableView);

        /**
         * 设置周次选择属性
         */
        mWeekView.curWeek(1)
                .callback(new IWeekView.OnWeekItemClickedListener() {
                    @Override
                    public void onWeekClicked(int week) {
                        int cur = mTimetableView.curWeek();
                        /**
                         * 更新切换后的日期，从当前周cur->切换的周week
                         */
                        mTimetableView.onDateBuildListener()
                                .onUpdateDate(cur, week);
                        mTimetableView.changeWeekOnly(week);
                    }
                })
                .callback(new IWeekView.OnWeekLeftClickedListener() {
                    @Override
                    public void onWeekLeftClicked() {
                        onWeekLeftLayoutClicked();
                    }
                })
                /**
                 * 设置隐藏，默认显示
                 */
                .isShow(false)
                .showView();

        mTimetableView.curWeek(1)
                .curTerm("大三下学期")
                .callback(new ISchedule.OnItemClickListener() {
                    @Override
                    public void onItemClick(Component v, List<Schedule> scheduleList) {
                        display(scheduleList);
                    }
                })
                .callback(new ISchedule.OnItemLongClickListener() {
                    @Override
                    public void onLongClick(Component v, int day, int start) {
                        ToastViewDialog.toast(SimpleSlice.this, "长按:周" + day + ",第" + start + "节");
                    }
                })
                .callback(new ISchedule.OnWeekChangedListener() {
                    @Override
                    public void onWeekChanged(int curWeek) {
                        titleTextView.setText("第" + curWeek + "周");
                    }
                })
                .callback(new OnItemBuildAdapter() {
                    @Override
                    public void onItemUpdate(StackLayout stackLayout, Text textView, Text countTextView,
                                             Schedule schedule, ShapeElement gd) {
                        super.onItemUpdate(stackLayout, textView, countTextView, schedule, gd);
                        if (schedule.getName().equals("【广告】")) {
                            stackLayout.removeAllComponents();
                            Image imageView = new Image(SimpleSlice.this);
                            imageView.setHeight(DependentLayout.LayoutConfig.MATCH_PARENT);
                            imageView.setWidth(DependentLayout.LayoutConfig.MATCH_PARENT);
                            stackLayout.addComponent(imageView);
                            String url = (String) schedule.getExtras().get(MySubject.EXTRAS_AD_URL);

                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    PixelMap pixelMap = loadImage(url);
                                    if (pixelMap != null) {
                                        /**
                                         * 普通解码
                                         */
                                        getUITaskDispatcher().syncDispatch(() -> {
                                            imageView.setPixelMap(pixelMap);
                                            pixelMap.release();
                                        });
                                    }
                                }
                            }).start();

                            imageView.setClickedListener(new Component.ClickedListener() {
                                @Override
                                public void onClick(Component component) {
                                    ToastViewDialog.toast(SimpleSlice.this, "进入广告网页链接");
                                }
                            });
                        }

                    }
                })
                .showView();
    }

    /**
     * 周次选择布局的左侧被点击时回调<br/>
     * 对话框修改当前周次
     */
    protected void onWeekLeftLayoutClicked() {
        final ArrayList items = new ArrayList();
        int itemCount = mWeekView.itemCount();
        for (int i = 0; i < itemCount; i++) {
            WeekChooseBean bean = new WeekChooseBean();
            bean.setWeek("第" + (i + 1) + "周");
            if (i == 0) {
                bean.setSelect(true);
            } else {
                bean.setSelect(false);
            }
            items.add(bean);
        }

        ChooseWeekDialog chooseWeekDialog = new ChooseWeekDialog(this, mTimetableView.curWeek() - 1);
        chooseWeekDialog.setTitle("设置当前周");
        chooseWeekDialog.setData(items);
        chooseWeekDialog.setmConfimClickListen(new ChooseWeekDialog.ConfimClickListen() {
            @Override
            public void onConfimClick(int index) {
                target = index;
                if (target != -1) {
                    mWeekView.curWeek(target + 1).updateView();
                    mTimetableView.changeWeekForce(target + 1);
                }
            }
        });
        chooseWeekDialog.setCancleButton(new ChooseWeekDialog.CancleClickListen() {
            @Override
            public void onCancleClick() {
            }
        });
        chooseWeekDialog.show();
    }

    /**
     * 显示内容
     *
     * @param beans
     */
    protected void display(List<Schedule> beans) {
        StringBuffer s = new StringBuffer();
        for (Schedule bean : beans) {
            s.append(bean.getName() + "," + bean.getWeekList().toString() + ","
                    + bean.getStart() + "," + bean.getStep() + "\n");
        }
        String str = s.toString();
        ToastViewDialog.toast(this, str);
    }

    /**
     * 隐藏周次选择，此时需要将课表的日期恢复到本周并将课表切换到当前周
     */
    public void hideWeekView() {
        mWeekView.isShow(false);
        mTimetableView.setShowWeekView(false);
        titleTextView.setTextColor(new Color(Color.rgb(19, 176, 241)));
        int cur = mTimetableView.curWeek();
        mTimetableView.onDateBuildListener()
                .onUpdateDate(cur, cur);
        mTimetableView.changeWeekOnly(cur);
    }

    /**
     * showWeekView
     */
    public void showWeekView() {
        mWeekView.isShow(true);
        mTimetableView.setShowWeekView(true);
        titleTextView.setTextColor(Color.RED);
    }

    /**
     * loadImage
     *
     * @param urlImage
     * @return PixelMap
     */
    public PixelMap loadImage(String urlImage) {
        PixelMap pixelMap = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlImage);
            URLConnection urlConnection = url.openConnection();
            if (urlConnection instanceof HttpURLConnection) {
                connection = (HttpURLConnection) urlConnection;
            }
            if (connection != null) {
                connection.connect();
                /**
                 * 之后可进行url的其他操作
                 * 得到服务器返回过来的流对象
                 */
                InputStream inputStream = urlConnection.getInputStream();
                ImageSource imageSource = ImageSource.create(inputStream, new ImageSource.SourceOptions());
                ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
                decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
                /**
                 * 普通解码叠加旋转、缩放、裁剪
                 */
                pixelMap = imageSource.createPixelmap(decodingOptions);

            }

        } catch (MalformedURLException e) {
            LogUtils.error("MalformedURLException:",e.toString());
        } catch (IOException e) {
            LogUtils.error("IOException:",e.toString());
        }
        return pixelMap;
    }
}
